package tessk.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.alibaba.fastjson.JSON;

import tessk.common.def.JsonResult;
import tessk.common.def.ResultEnum;
import tessk.config.Audience;
import tessk.jwt.JwtHelper;

public class AuthorizeFilter implements Filter{

	@Autowired
	private Audience audienceEntity;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,  
                filterConfig.getServletContext());  
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
	    HttpServletRequest httpRequest = (HttpServletRequest) request;
	    String auth = httpRequest.getHeader("Authorization");
	    if(StringUtils.isNotEmpty(auth)){
	    	if(JwtHelper.parestJWT(auth, audienceEntity.getBase64Secret()) !=null){
	    		chain.doFilter(request, response);
	    		return;
	    	}
	    }
	    HttpServletResponse httpResponse = (HttpServletResponse) response;  
        httpResponse.setCharacterEncoding("UTF-8");    
        httpResponse.setContentType("application/json; charset=utf-8");   
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  
  
          
        httpResponse.getWriter().write(JSON.toJSONString(new JsonResult(ResultEnum.LOGIN_OUT_TIME)));  
        return;  
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
